package com.sixth.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @ClassName IntegerArrayTypeHandler
 * @Description
 * @Author XiaoWJ
 * @Date 2022/9/7 13:50
 **/

@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]> {

    ObjectMapper objectMapper = new ObjectMapper();

    // 输入映射，Integer[]映射为String
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, Integer[] integers, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(integers);

        // 为位置为index的参数设置值为value
        preparedStatement.setString(index,value);
    }


    // 三种输出映射
    @Override
    public Integer[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        String result = resultSet.getString(columnName);

        return transfer(result);
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, int index) throws SQLException {
        String result = resultSet.getString(index);
        return transfer(result);

    }

    @Override
    public Integer[] getResult(CallableStatement callableStatement, int index) throws SQLException {
        String result = callableStatement.getString(index);
        return transfer(result);

    }

    // 通过Json工具将string转化为Integer[]
    @SneakyThrows
    private Integer[] transfer(String result) {
        if (result == null) {
            return null;
        }
        return objectMapper.readValue(result, Integer[].class);
    }
}
